package sample.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisUtil {

    @Autowired
    RedisTemplate redisTemplate;


    /********************Key-value操作*********************/

    /**
     * 添加key-value
     * @param key
     * @param value
     */
    public void set(String key,Object value){
        redisTemplate.boundValueOps(key).set(value);
    }

    public Object get(String key){
       return redisTemplate.boundValueOps(key).get();
    }

    /**
     * 删除key-value
     * @param key
     */
    public void delete(String key){
        redisTemplate.delete(key);
    }

    /**
     * 为某个键设置过期时间
     * @param key
     * @param timeout
     */
    public void expire(String key,long timeout){
        redisTemplate.expire(key,timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 自增（默认1）
     * @param key
     * @param timeout
     */
    public void increment(String key,long timeout){
        redisTemplate.boundValueOps(key).increment();
    }

    /******************HASHMAP操作******************/

    public void putMap(String mapName,String key,Object value){
        redisTemplate.boundHashOps(mapName).put(key,value);
    }

    public Object getMap(String mapName,String key){
        return redisTemplate.boundHashOps(mapName).get(key);
    }

    /**
     * 插入某个map中所有键值对
     * @param mapName
     * @param map
     */
    public void putMapAll(String mapName, Map map){
        redisTemplate.boundHashOps(mapName).putAll(map);
    }

    /**
     * 获取所有key
     * @param mapName
     */
    public Set getMapKeys(String mapName){
        return redisTemplate.boundHashOps(mapName).keys();
    }

    /**
     * 获取所有value
     * @param mapName
     * @return
     */
    public List getMapValues(String mapName){
        return redisTemplate.boundHashOps(mapName).values();
    }

    /**
     * 返回整个Map
     * @param mapName
     * @return
     */
    public Map getAllMap(String mapName){
        return redisTemplate.boundHashOps(mapName).entries();
    }

    public void deleteMap(String mapName,String key){
        redisTemplate.boundHashOps(mapName).delete(key);
    }

}
